
=begin
  TODOs:
    - Cleanup duplicate tasks
    - Condense number of tasks to:
      - Testing
      - Compilation
      - Compression (compact using YUI compressor)
      - Deployment     
=end




namespace :js do
  require 'fileutils'
  #require 'zip/zip' #gem install rubyzip -> http://rubyzip.sourceforge.net/
  require 'net/http'
  require "sprockets" #gem install --remote sprockets  -> http://github.com/sstephenson/sprockets/
  require 'yaml'
  #require 'ftools'
  require 'find' #FOR .svn deletion
  require 'webrick'
  include WEBrick
  
  

  task :server, :appname do |t, args|
      dir = args[:appname] ?  args[:appname] : Dir::pwd
      port = 12000 + (dir.hash % 1000)
      puts "URL: http://localhost:#{port}"
      s = HTTPServer.new(:Port => port, :DocumentRoot => dir)
      trap("INT"){ s.shutdown }
      s.start
  end

 
=begin
    USAGE:
        rake js:webrick
        rake js:webrick["HelloWorld_App"]
=end
  task :webrick, :appname do |t, args|
      dir = args[:appname] ?  args[:appname] : Dir::pwd
      sh %{ruby framework/buildtools/simpleserver/webrick.rb -p 3300 -d #{dir}}
  end
  
  #  task :doc, :appname, :controlname do |t, args| 
  #     controls_name =   "#{args[:controlname]}"
  #     doctoolkit_path = "#{args[:appname]}/cdn/buildtools/jsdoc-toolkit"
  #     sh %{java -jar #{doctoolkit_path}/jsrun.jar  #{doctoolkit_path}/app/run.js -t=#{doctoolkit_path}/templates/jsdoc -d=#{args[:appname]}/docs/ -r=9 #{args[:appname]}/cdn/controls/#{controls_name}/js/#{controls_name}.js}
  #  end
  
  namespace :generate do
    task :application, :appname do |t, args| 
      FileUtils.cp_r "framework/samples/applications/helloworld/", "#{args[:appname]}/"
      Dir.glob("#{args[:appname]}/**/.svn") do |dir|
        FileUtils.remove_dir(dir,true)
      end
      
      lines = File.open("#{args[:appname]}/config/sprockets-options.yml","r").readlines
      lines.each do |line|
        if line =~ /appname/
          line.gsub!(/appname/, args[:appname])
        end
      end
      File.open("#{args[:appname]}/config/sprockets-options.yml","w").write(lines)
      
      
      lines = File.open("#{args[:appname]}/application.js","r").readlines
      lines.each do |line|
        if line =~ /APPNAME/
          line.gsub!(/APPNAME/, args[:appname])
        end
      end
      File.open("#{args[:appname]}/application.js","w").write(lines)
      
      
      lines = File.open("#{args[:appname]}/index.html","r").readlines
      lines.each do |line|
        if line =~ /APPNAME/
          line.gsub!(/APPNAME/, args[:appname])
        end
        if line =~ /appnamelc/
          line.gsub!(/appnamelc/, args[:appname].downcase)
        end
      end
      File.open("#{args[:appname]}/index.html","w").write(lines)
      
      puts "\n\n\n"
      puts "SUCCESSFULLY CREATED APPLICATION: " + args[:appname]
      puts "IMPORTANT:\n\tPlease modify config in #{args[:appname]}/config/sprockets-options.yml"
    end
  end
  
  namespace :tomcat do  
    task :deploy, :appname, :refresh_cdn do |t, args| 
      sh %{rake js:build:application["#{args[:appname]}"]} 
      sunray_config = YAML::load( File.open( "#{args[:appname]}/config/sprockets-options.yml" ))
      app_name = args[:appname]
      deploypath = sunray_config["deployment"]["localhost"]
      do_cdn_refresh = args[:refresh_cdn]
      
      FileUtils.remove_dir("#{deploypath}/#{args[:appname]}",true)
      FileUtils.mkdir_p "#{deploypath}/#{args[:appname]}"
      FileUtils.cp_r "#{args[:appname]}/", deploypath
      FileUtils.cp_r "Rakefile", "#{deploypath}/Rakefile"
      #FileUtils.remove_dir("#{deploypath}/#{args[:appname]}/config",true)
      
    #BEGIN .svn deletion
#     require 'find'
#     require 'fileutils'
      Find.find(deploypath) do |path|
        if File.basename(path).match(/\.svn/)
          FileUtils.remove_dir(path, true)
          Find.prune
        end
        if File.basename(path).match(/^.tmp\_/)
          FileUtils.remove_dir(path, true)
          Find.prune
        end
      end
      #END .svn deletion
    end
  end
  
  #namespace :build do
    task :build, :appname do |t, args|   
      app_name = args[:appname] || nil
      if app_name then
        app_name = app_name + "/"
      else
        app_name = ""
      end
      
      sunray_config = YAML::load( File.open( "#{app_name}config/sprockets-options.yml" ) )
      jspaths = sunray_config["load paths"]
      jsmodifiedpaths = []
      jspaths.each { |path| 
        jsmodifiedpaths << path
      } 
      runtime  = ["#{app_name}config/sprockets-dependencies.js"]
      
      secretary = Sprockets::Secretary.new(
                                           :asset_root   => "public", :load_path    => jspaths, :source_files => runtime
      )
      concatenation   = secretary.concatenation
      outputpath    = sunray_config["output location"]["runtime"]
      compressedPath  = sunray_config["output location"]["compressed"]
      concatenation.save_to(outputpath)
      
      if File.exist?("../framework/src/runtime.js") then
        FileUtils.cp_r "../framework/src/runtime.js", "#{app_name}cdn/src/framework.js"
        FileUtils.cp_r "../framework/src/runtime.min.js", "#{app_name}cdn/src/framework.min.js"
      end
      #sh %{java -jar buildtools/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar #{outputpath} -o #{compressedPath} --line-break 200}
      #sh %{ java org.mozilla.javascript.tools.shell.Main application/tools/jslint.js runtime.js }
    end
    
    task :doc, :appname do |t, args|
      if args[:appname] then
        sh %{java -jar framework/buildtools/jsdoc-toolkit/jsrun.jar framework/buildtools/jsdoc-toolkit/app/run.js -a -t=framework/buildtools/jsdoc-toolkit/templates/jsdoc -d=#{args[:appname]}/src/doc -r=10 #{args[:appname]}/}
      else
        sh %{java -jar framework/buildtools/jsdoc-toolkit/jsrun.jar framework/buildtools/jsdoc-toolkit/app/run.js -a -t=framework/buildtools/jsdoc-toolkit/templates/jsdoc -d=framework/src/doc -r=10 framework/}
      end
    end
  
    task :runtime, :appname do |t, args|   
      sunray_config = YAML::load( File.open( "framework/config/sprockets-options.yml" ) )
      jspaths = sunray_config["load paths"]
      jsmodifiedpaths = []
      jspaths.each { |path| 
        jsmodifiedpaths << "framework" + path
      } 
      
      config  = ["framework/config/config.js"]
      ui  = ["framework/config/framework.js"]
      runtime = ui
      secretary = Sprockets::Secretary.new(
                                           :asset_root   => "public", :load_path    => jsmodifiedpaths, :source_files => runtime
      )
      concatenation = secretary.concatenation
      outputpath = sunray_config["output location"]["runtime"]
      compressedPath = sunray_config["output location"]["compressed"]
      concatenation.save_to(outputpath)
      
      sh %{java -jar framework/buildtools/yuicompressor-2.4.2/yuicompressor-2.4.2.jar #{outputpath} -o #{compressedPath} --line-break 200}
      #sh %{ java org.mozilla.javascript.tools.shell.Main application/tools/jslint.js runtime.js }
      #File.delete("#{args[:appname]}/bootloader.js")
    end
  #end
  
  namespace :install do
    desc "Installs a compressed (.zip) javascript application"
    task :app, :appname, :version do |t, args|
      v = args[:version]
      appname = "#{args[:appname]}" + "-" + v + ".zip"
      filepath = "/files/" + appname
      
      Net::HTTP.start("sunray-ui-toolkit.googlecode.com") { |http|
        resp = http.get(filepath)
        open(appname, "wb") { |file|
          file.write(resp.body)
        }
        unzip_file(appname, "#{args[:appname]}")
        File.delete(appname)
        sh %{rake js:compress:app["#{args[:appname]}"]} 
      }
      puts "Successfully installed #{args[:appname]}"
    end
    
    task :control, :ctrlname, :version, :appname do |t, args|
      def unzip_control (file, destination)
        Zip::ZipFile.open(file) { |zip_file|
          zip_file.each { |f|
            f_path=File.join(destination, f.name)
            FileUtils.mkdir_p(File.dirname(f_path))
            zip_file.extract(f, f_path) unless File.exist?(f_path)
          }
        }
      end
      
      v = args[:version]
      appname = "#{args[:ctrlname]}" + "-" + v + ".zip"
      httpfilepath = "/files/" + appname
      diskfilepath = "#{args[:appname]}/library/controls/#{appname}"
      repository_host = "sunray-ui-toolkit.googlecode.com"
      puts "appname: #{appname}"
      puts "httpfilepath: #{httpfilepath}"
      puts "diskfilepath: #{diskfilepath}"
      puts "repository_host: #{repository_host}"
      
      
      Net::HTTP.start(repository_host) { |http|
        resp = http.get(httpfilepath)
        open(diskfilepath, "wb") { |file|
          file.write(resp.body)
        }
        unzip_control(diskfilepath, "#{args[:appname]}/library/controls/")
        File.delete(diskfilepath)
      }
      puts "\n\n\nSUCCESSFULLY INSTALLED CONTROL: #{args[:ctrlname]}"
    end
  end
  
  
end


def unzip_file (file, destination)
  Zip::ZipFile.open(file) { |zip_file|
    zip_file.each { |f|
      f_path=f.name #File.join(destination, f.name)
      FileUtils.mkdir_p(File.dirname(f_path))
      zip_file.extract(f, f_path) unless File.exist?(f_path)
    }
  }
end